import time
import requests

import coin.exchange.base.kr_rest.native_public_client_base as npubcb
import coin.exchange.base.kr_rest.rest_client_base as rcb


class GeminiNativePublicClient(npubcb.NativePublicClientBase):
  def __init__(self, timeout=1):
    npubcb.NativePublicClientBase.__init__(self, url="https://api.gemini.com/v1", timeout=timeout)

  def _get_as_json(self, path, params=None, headers=None):
    req_timestamp = time.time()
    full_url = "%s/%s" % (self.url, path)
    r = requests.get(full_url, headers=headers, params=params, timeout=self.timeout)
    if r.status_code == requests.codes.ok:
      res_timestamp = time.time()
      return rcb.RestUpdate(req_timestamp, res_timestamp, r.json())
    else:
      res_timestamp = time.time()
      # If a response is in error, then the HTTP response code will be set to
      # reflect this, and a JSON body will be returned that will contain
      # information about the failure.
      try:
        res_json = r.json()
      except ValueError:
        res_json = None
      return rcb.RestUpdate(req_timestamp, res_timestamp, res_json, status=r.status_code)

  def get_symbols(self):
    return self._get_as_json("symbols")

  def get_pubticker(self, symbol):
    return self._get_as_json("pubticker/%s" % symbol)

  def get_book(self, symbol, limit_bids=None, limit_asks=None):
    # If a parameter value is None, then the parameter will not be encoded in
    # the query sting.
    params = {
        'limit_bids': limit_bids,
        'limit_asks': limit_asks,
    }
    return self._get_as_json("book/%s" % symbol, params=params)

  def queryAll(self):
    symbol = "btcusd"
    print(self.get_book(symbol))


if __name__ == "__main__":
  client = GeminiNativePublicClient(timeout=10)
  client.queryAll()
